package com.ruoyi.lvlian.service.impl;

import java.util.stream.Collectors;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;

import cn.hutool.core.img.Img;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.MD5Utils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.lvlian.dto.InvoiceInfoDto;
import com.ruoyi.lvlian.dto.WarehouseInfoDto;
import com.ruoyi.lvlian.util.ExcelUtil;
import com.ruoyi.lvlian.vo.WarehouseInfoVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.lvlian.mapper.WarehouseInfoMapper;
import com.ruoyi.lvlian.domain.WarehouseInfo;
import com.ruoyi.lvlian.service.IWarehouseInfoService;
import org.springframework.web.multipart.MultipartFile;

/**
 * 入库单Service业务层处理
 *
 * @author liyuxi
 * @date 2024-07-19
 */
@Service
public class WarehouseInfoServiceImpl implements IWarehouseInfoService {
    @Autowired
    private WarehouseInfoMapper warehouseInfoMapper;


    /**
     * 查询入库单
     *
     * @param id 入库单主键
     * @return 入库单
     */
    @Override
    public WarehouseInfoVo selectWarehouseInfoById(String id) {

        WarehouseInfoVo vo = warehouseInfoMapper.selectWarehouseInfoById(id);
//        刷新图片
        //            更新图片操作
        int result=0;
        if(StringUtils.isEmpty(vo.getLoadWeightImg() )){
            result= warehouseInfoMapper.updateWarehouseInfoImg(id,"load_weight_img" );
        }
        if(StringUtils.isEmpty(vo.getInNumImg() )){
            result= warehouseInfoMapper.updateWarehouseInfoImg(id,"in_num_img" );
        }


        if(StringUtils.isEmpty(vo.getOutNumImg() )){
            result= warehouseInfoMapper.updateWarehouseInfoImg(id,"out_num_img" );
        }


        if(StringUtils.isEmpty(vo.getInWeighNumImg() )){
            result= warehouseInfoMapper.updateWarehouseInfoImg(id,"in_weigh_num_img" );
        }
        if(StringUtils.isEmpty(vo.getUnloadImg() )){
            result= warehouseInfoMapper.updateWarehouseInfoImg(id,"unload_img" );
        }

        if(StringUtils.isEmpty(vo.getLoadImg() )){
            result= warehouseInfoMapper.updateWarehouseInfoImg(id,"load_img" );
        }

        if(StringUtils.isEmpty(vo.getOutGrossWeightImg() )){
            result= warehouseInfoMapper.updateWarehouseInfoImg(id,"out_gross_weight_img" );
        }

        if(StringUtils.isEmpty(vo.getOutWeighNumImg() )){
            result= warehouseInfoMapper.updateWarehouseInfoImg(id,"out_weigh_num_img" );
        }



        return vo;
    }



/*    update lv_warehouse_info   a1
    LEFT join lv_file_attachment_info   a2   on a1.id  = LEFT(association_id,32)
    set   load_weight_img  = 		a2.id
    where  table_name ='lv_warehouse_info'  and col_name ='load_weight_img' and a2.create_user ='小程序'
    and  a1.id = 'bd87e4d4e10003038602e8fd3a02d55b'*/


    /**
     * 查询入库单列表
     *
     * @param inWarehouseInfo 入库单
     * @return 入库单
     */
    @Override
    public List<WarehouseInfoVo> selectWarehouseInfoList(WarehouseInfoDto inWarehouseInfo) {


        if (StringUtils.isNotEmpty(inWarehouseInfo.getOrderNum())) {
            List<WarehouseInfoVo> warehouseInfoVos = warehouseInfoMapper.queryInWarehouseInfoListByOrderNum(inWarehouseInfo);
            for (WarehouseInfoVo po : warehouseInfoVos) {
                po.setDriverLicenseImg(warehouseInfoMapper.getFileImageId(po.getDriverLicense(), "driver_license_img"));
                po.setDrivingLicenseImg(warehouseInfoMapper.getFileImageId(po.getPlateNo(), "driving_license_img"));
            }
            return warehouseInfoVos;
        }


        if (StringUtils.isNotEmpty(inWarehouseInfo.getInvoiceNum())) {
            List<WarehouseInfoVo> warehouseInfoVos = warehouseInfoMapper.queryInWarehouseInfoListByInvoiceNum(inWarehouseInfo);
            for (WarehouseInfoVo po : warehouseInfoVos) {
                po.setDriverLicenseImg(warehouseInfoMapper.getFileImageId(po.getDriverLicense(), "driver_license_img"));
                po.setDrivingLicenseImg(warehouseInfoMapper.getFileImageId(po.getPlateNo(), "driving_license_img"));
            }

            return warehouseInfoVos;
        }

        List<WarehouseInfoVo> list = warehouseInfoMapper.selectWarehouseInfoList(inWarehouseInfo);
        for (WarehouseInfoVo po : list) {
            InvoiceInfoDto invoiceInfo = new InvoiceInfoDto();
            invoiceInfo.setBuyerName(po.getBuyerName());
            invoiceInfo.setSellerName(po.getSellerName());

            if ("采购物流结算".equalsIgnoreCase(po.getCategory())) {
                po.setBuyerSettlementAmountRef(warehouseInfoMapper.queryInvoiceInfoWarehouseInfoRef(po.getInNum(), po.getBuyerName(), po.getSellerName(), po.getPlateNo()));
                if (StringUtils.isNotEmpty(inWarehouseInfo.getLicenseNo())) {
                    invoiceInfo.setInNum(po.getInNum());
                    po.setDriverLicenseImg(warehouseInfoMapper.getFileImageId(po.getDriverLicense(), "driver_license_img"));
                    po.setDrivingLicenseImg(warehouseInfoMapper.getFileImageId(po.getPlateNo(), "driving_license_img"));
                }
            } else {
                po.setSellerSettlementAmountRef(warehouseInfoMapper.queryInvoiceInfoWarehouseInfoRef(po.getOutNum(), po.getBuyerName(), po.getSellerName(), po.getPlateNo()));
                if (StringUtils.isNotEmpty(inWarehouseInfo.getLicenseNo())) {
                    invoiceInfo.setInNum(po.getOutNum());
                    po.setDriverLicenseImg(warehouseInfoMapper.getFileImageId(po.getDriverLicense(), "driver_license_img"));
                    po.setDrivingLicenseImg(warehouseInfoMapper.getFileImageId(po.getPlateNo(), "driving_license_img"));
                }
            }

            invoiceInfo = null;
        }

        if (inWarehouseInfo.getInHaveImg() != null && inWarehouseInfo.getInHaveImg()) {
            // 异步执行
            new Thread(() -> processWarehouseRefImages("in")).start();
        }
        if (inWarehouseInfo.getOutHaveImg() != null && inWarehouseInfo.getOutHaveImg()) {
            // 异步执行
            new Thread(() -> processWarehouseRefImages("out")).start();
        }
        return list;
    }


    public void processWarehouseRefImages(String type) {
        // 这里是你的业务逻辑
        try {
            if ("in".equalsIgnoreCase(type)) {
                warehouseInfoMapper.processWarehouseRefInImages();
            } else {
                warehouseInfoMapper.processWarehouseRefOutImages();
            }

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 新增入库单
     *
     * @param inWarehouseInfo 入库单
     * @return 结果
     */
    @Override
    public int insertWarehouseInfo(WarehouseInfo inWarehouseInfo) {
        inWarehouseInfo.setId(MD5Utils.md5(inWarehouseInfo.getInNum() + inWarehouseInfo.getBuyerName() + inWarehouseInfo.getInDate() + inWarehouseInfo.getBuyerSettlementAmount()));
        inWarehouseInfo.setDataSource("实时物流小程序");
        inWarehouseInfo.setCreateUser(SecurityUtils.getUsername());
        inWarehouseInfo.setCreateDate(DateUtils.getCurrentTime());
        return warehouseInfoMapper.insertWarehouseInfo(inWarehouseInfo);
    }

    /**
     * 修改入库单
     *
     * @param inWarehouseInfo 入库单
     * @return 结果
     */
    @Override
    public int updateWarehouseInfo(WarehouseInfo inWarehouseInfo) {

        int updateResult = warehouseInfoMapper.updateWarehouseInfo(inWarehouseInfo);
        if (0 == updateResult) {
            updateResult = insertWarehouseInfo(inWarehouseInfo);
        }

        return updateResult;

    }

    /**
     * 批量删除入库单
     *
     * @param ids 需要删除的入库单主键
     * @return 结果
     */
    @Override
    public int deleteWarehouseInfoByIds(String[] ids) {
        return warehouseInfoMapper.deleteWarehouseInfoByIds(ids);
    }

    /**
     * 删除入库单信息
     *
     * @param id 入库单主键
     * @return 结果
     */
    @Override
    public int deleteWarehouseInfoById(String id) {
        return warehouseInfoMapper.deleteWarehouseInfoById(id);
    }

    @Override
    public List<WarehouseInfo> importInfo(MultipartFile file, String sheetName, int rowNum) throws Exception {
        byte[] fileBytes = file.getBytes();
        List<WarehouseInfo> invoiceRecyclingInfos = ExcelUtil.readExcel(fileBytes, WarehouseInfo.class, sheetName, rowNum);
        return invoiceRecyclingInfos;
    }

    @Override
    public int bachSave(List<WarehouseInfo> dtoList) {
        int saveBatch = 0;
        if (!dtoList.isEmpty()) {
            List<String> warehouseNumList = warehouseInfoMapper.queryWarehouseNum();


            List<WarehouseInfo> newList = new ArrayList<>();
            for (WarehouseInfo po : dtoList) {
                if (StringUtils.isEmpty(po.getOrgCode()) || StringUtils.isEmpty(po.getInNum()) || StringUtils.isEmpty(po.getSellerName())
                        || StringUtils.isEmpty(po.getBuyerName()) || StringUtils.isEmpty(po.getPlateNo()) || StringUtils.isEmpty(po.getDriverName())
                ) {
                    continue;
                }


                String id = po.getInNum();
                if ("销售物流结算".equalsIgnoreCase(po.getCategory())) {
                    if (StringUtils.isEmpty(po.getOutDate()) || po.getSellerSettlementAmount() == 0) {
                        continue;
                    }
                    if("41110101".equalsIgnoreCase(po.getOrgCode())){
                        id = MD5Utils.md5(po.getOrgCode() + po.getUid() + po.getInNum() + po.getBuyerContractNum() + po.getSellerName() + po.getBuyerName() + po.getPlateNo() + po.getDriverName() + po.getOutDate() + po.getSellerSettlementAmount());
                    }else {
                        id = MD5Utils.md5(po.getOrgCode() + po.getOutNum() + po.getInNum() + po.getBuyerContractNum() + po.getSellerName() + po.getBuyerName() + po.getPlateNo() + po.getDriverName() + po.getOutDate() + po.getSellerSettlementAmount());

                    }
                } else if ("采购物流结算".equalsIgnoreCase(po.getCategory())) {
                    if (StringUtils.isEmpty(po.getInDate()) || po.getBuyerSettlementAmount() == 0) {
                        continue;
                    }
                    if("41110101".equalsIgnoreCase(po.getOrgCode())){
                        id = MD5Utils.md5(po.getOrgCode() + po.getUid() + po.getBuyerContractNum() + po.getSellerName() + po.getBuyerName() + po.getPlateNo() + po.getDriverName() + po.getInDate() + po.getBuyerSettlementAmount());

                    }else {
                        id = MD5Utils.md5(po.getOrgCode() + po.getInNum() + po.getBuyerContractNum() + po.getSellerName() + po.getBuyerName() + po.getPlateNo() + po.getDriverName() + po.getInDate() + po.getBuyerSettlementAmount());
                    }

                } else {
                    continue;
                }

                po.setId(id);
                po.setCreateUser(SecurityUtils.getUsername());
                po.setCreateDate(DateUtils.getCurrentTime());
                po.setDataSource("四流平台");

//                加入之前做个判断 ，如果是小程序已经加入了 ，那么就不用再加到库中

                if ("销售物流结算".equalsIgnoreCase(po.getCategory())) {
                    if (!warehouseNumList.contains(po.getOutNum())) {
                        newList.add(po);
                    }
                } else if ("采购物流结算".equalsIgnoreCase(po.getCategory())) {
                    if (!warehouseNumList.contains(po.getInNum())) {
                        newList.add(po);
                    }else{
                        System.out.println( "包含的有   =="+ po.getInNum());
                    }
                }


            }
            if (!newList.isEmpty()) {
                saveBatch = warehouseInfoMapper.batchSave(newList);
            }
        }

        return saveBatch;
    }

    @Override
    public WarehouseInfoVo getInfoByOther(String category, String warehouseNum, String plateNo) {
        WarehouseInfoVo vo = warehouseInfoMapper.getInfoByOther(category, warehouseNum, plateNo);

        return vo;
    }
}
